package com.hjb.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hjb.annotation.UsingDb;
import com.hjb.entity.Database;
import com.hjb.mapper.DatabaseMapper;
import com.hjb.service.IDatabaseService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.aop.framework.AopContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author HuJiaBing
 * @date 2025/7/4 10:34
 * @description
 */
@Slf4j
@Service
public class DatabaseServiceImpl extends ServiceImpl<DatabaseMapper,Database> implements IDatabaseService {

    @Override
    public List<Database> listAll() {
        return this.baseMapper.selectList(new QueryWrapper<>());
    }

    @Override
    public void saveDatabase(Database database) {
        this.saveOrUpdate(database);
    }

    @Override
    public void deleteDatabase(String id) {
        this.removeById(id);
    }

    @Override
    @UsingDb("slave")
    public List<Database> listDiff() {
        return this.baseMapper.selectList(new QueryWrapper<>());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateDatabase() {
        ((IDatabaseService)AopContext.currentProxy()).updateDb1();
        ((IDatabaseService)AopContext.currentProxy()).updateDb2();
        log.info("更新完成");
        throw new RuntimeException("手动抛错");
    }
    @Override
    @UsingDb("slave")
    // 如果不新开事务，则不会切换数据源
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRES_NEW)
//    @Transactional(rollbackFor = Exception.class)
    public void updateDb1() {
        LambdaUpdateWrapper<Database> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(Database::getDbName, "spring_ds2");
        wrapper.set(Database::getRemark, String.valueOf(System.currentTimeMillis()));
        this.update(wrapper);
    }
    @Override
    @UsingDb("main")
    // 如果不新开事务，则不会切换数据源
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRES_NEW)
//    @Transactional(rollbackFor = Exception.class)
    public void updateDb2() {
        LambdaUpdateWrapper<Database> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(Database::getDbName, "spring_ds");
        wrapper.set(Database::getRemark, String.valueOf(System.currentTimeMillis()));
        this.update(wrapper);
    }
}
